package com.easysoft.commons.servlet;

import com.easysoft.commons.utils.DateTimeUtils;
import com.easysoft.commons.utils.JSONUtils;
import com.easysoft.commons.utils.RandomUtils;
import com.easysoft.commons.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;


public class UploadFileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, Object> result = new HashMap<>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest = multipartResolver.resolveMultipart(request);
            Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
            int count = 0, size = 0;
            List<String> allPath = new ArrayList<>();

            while (fileNames.hasNext()) {
                MultipartFile file = multipartHttpServletRequest.getFile(fileNames.next());

                if (file != null) {
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();

                    if (StringUtils.isNotNullAndBlank(myFileName.trim())) {
                        count++;
                        // 获取文件后缀名
                        String suffix = getSuffix(myFileName);

                        if (checkFileSuffix(suffix)) {
                            //重命名上传后的文件名
                            String fileName = DateTimeUtils.formatDateToString(new Date(), "yyyyMMddHHmmssSSS")+ RandomUtils.getRandomNumber(3)+ "." + suffix;
                            //定义上传路径
                            String path = "E:/temp/";
                            File localDir = new File(path);
                            if (!localDir.exists()) {
                                //noinspection ResultOfMethodCallIgnored
                                localDir.mkdirs();
                            }
                            File localFile = new File(localDir, fileName);
                            file.transferTo(localFile);
                            size++;
                            allPath.add(path + fileName);
                        }
                    }
                }
            }

            if (count == 0 || size == 0) {
                result.put("success", false);
                result.put("message", "上传失败");
            }

            if (count > 0 && size > 0) {
                result.put("success", true);
                result.put("message", "共" + count + "个文件,上传成功" + size + "个文件");
                result.put("path", allPath);
            }

        } else {
            result.put("success", false);
            result.put("message", "非 multipart/form-data");
        }

        String json = JSONUtils.object2Json(result);
        OutputStream out = response.getOutputStream();
        out.write(json.getBytes("utf-8"));
        out.flush();
        out.close();
    }

    private boolean checkFileSuffix(String suffix) {
        boolean flag = false;

        List<String> suffixList = new ArrayList<>();
        suffixList.add("jpg");
        suffixList.add("gif");
        suffixList.add("png");
        suffixList.add("ico");
        suffixList.add("bmp");
        suffixList.add("jpeg");

        if (suffixList.contains(suffix)) {
            flag = true;
        }

        return flag;
    }

    private String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
    }
}
